# -*- coding:utf-8 -*-
import json
import random

from util.phone_sender import PhoneSender
from util.redis_connect import RedisPoolConnect
# 缓存连接池
REDIS_POOL_PHONE = RedisPoolConnect(1)
# 验证短信发送服务
PHONE_SENDER = PhoneSender()


def handler(event, context):
    logger = context.getLogger()
    messages = event.get("records")[0].get("messages")
    for message in messages:
        logger.info(message)
        message = json.loads(message)
        contact = message.get("contact")
        verify_id = message.get("verifyId")
        user_name = message.get("userName")
        verification_code = "".join([str(random.randint(0, 9)) for i in range(6)])
        PHONE_SENDER.send_msg(contact, f"['{verification_code}']")
        key = f"{verify_id}+{user_name}"
        REDIS_POOL_PHONE.set_key_value(key, verification_code)
